package com.dianplus.biz.auth.security;

import com.dianplus.biz.auth.domain.SysLogin;
import com.dianplus.biz.auth.repository.SysLoginRepository;
import com.dianplus.biz.security.DomainCustomDetails;
import com.dianplus.biz.security.exception.UserNotvalidException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.Set;


@Component
@Slf4j
public class DomainUserDetailsService implements UserDetailsService {

    @Autowired
    private SysLoginRepository sysLoginRepository;

    @Override
    public DomainCustomDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String lowcaseUsername = username.toLowerCase();
        Optional<SysLogin> login = sysLoginRepository.findOneWithRolesByLogin(lowcaseUsername);

        return login.map(user -> {
            if(!user.isValid()){
                new UserNotvalidException("用户" + lowcaseUsername + "不存在!");
            }
            Set<GrantedAuthority> grantedAuthorities = user.getAuthorities();
            return new DomainCustomDetails(user.getId(), user.getLogin(),user.getPassword(),grantedAuthorities);
        }).orElseThrow(() -> new UsernameNotFoundException("用户" + lowcaseUsername + "不存在!"));
    }
}
